package com.wptk.filemanager.ui.file;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.wptk.filemanager.R;
import com.wptk.filemanager.model.DialogManager;
import com.wptk.filemanager.model.file.FileBean;
import com.wptk.filemanager.model.file.FileManager;
import com.wptk.filemanager.model.file.FileUtils;
import com.wptk.filemanager.ui.base.BaseActivity;
import com.wptk.filemanager.ui.base.BaseFragment;
import com.wptk.filemanager.ui.file.adapter.DocsRVAdapter;
import com.wptk.filemanager.utils.ThreadManager;
import com.wptk.filemanager.utils.Utils;
import com.kathline.library.util.ZFileUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DocFragment extends BaseFragment implements View.OnClickListener, DocsRVAdapter.OnLongClickListener, DocsRVAdapter.OnClickListener {

    private final static String TAG = "DocFragment";
    private RecyclerView rv;
    private DocsRVAdapter docsRVAdapter;
    private String type = "";

    private LinearLayout modifyLl;
    private SwipeRefreshLayout refreshLayout;
    private LinearLayout emptyLayout;
    private TextView renameTv;
    private TextView deleteTv;
    private int typeNum;
    private List<FileBean> files;

    private OnSelectModelChangeListener onSelectModelChangeListener;

    public static DocFragment newInstance(String type,OnSelectModelChangeListener listener) {
        Bundle args = new Bundle();
        args.putString("type", type);
        DocFragment fragment = new DocFragment();
        fragment.setArguments(args);
        fragment.onSelectModelChangeListener = listener;
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        type = bundle.getString("type");
        typeNum = initType();
        Log.e(TAG, "type = " + type);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_docs;
    }

    @Override
    protected void initView(View rootView) {
        rv = rootView.findViewById(R.id.rv);
        modifyLl = rootView.findViewById(R.id.modify_ll);
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        emptyLayout = rootView.findViewById(R.id.emptyLayout);

        renameTv = rootView.findViewById(R.id.rename_tv);
        deleteTv = rootView.findViewById(R.id.delete_tv);
    }

    @Override
    protected void initEvent() {
        renameTv.setOnClickListener(this);
        deleteTv.setOnClickListener(this);
        refreshLayout.setEnabled(false);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });

        docsRVAdapter = new DocsRVAdapter(getContext());
        docsRVAdapter.setOnLongClickListener(this);
        docsRVAdapter.setOnClickListener(this);
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.setAdapter(docsRVAdapter);
        getData();
    }

    private int initType() {
        int typeNum = -1;
        if("All".equals(type)){
            typeNum = FileUtils.TYPE_DOC;
        }else if("PDF".equals(type)){
            typeNum = FileUtils.TYPE_PDF;
        }else if("Word".equals(type)){
            typeNum = FileUtils.TYPE_WORD;
        }else if("Excel".equals(type)){
            typeNum = FileUtils.TYPE_EXCEL;
        }else if("PPT".equals(type)){
            typeNum = FileUtils.TYPE_PPT;
        }else if("Other".equals(type)){
            typeNum = FileUtils.TYPE_OTHER;
        }
        return typeNum;
    }

    private void getData() {
        refreshLayout.setRefreshing(true);
        ThreadManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                files = FileManager.getInstance(Utils.getContext()).getDocsByType(typeNum);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (files == null || files.size() == 0) {
                            docsRVAdapter.clear();
                            emptyLayout.setVisibility(View.VISIBLE);
                        } else {
                            docsRVAdapter.setDatas(files);
                            rv.scrollToPosition(0);
                            emptyLayout.setVisibility(View.GONE);
                        }
                        refreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rename_tv:
                /*if(docsRVAdapter.getSelectDocs().isEmpty()){
                    showToast("请先选择要更名的文件");
                    return;
                }*/
                final FileBean renameFile = docsRVAdapter.getSelectDocs().get(0);

                DialogManager.renameDialog(getActivity()
                        , renameFile.getFilePath()
                        , renameFile.getFileName()
                        , new DialogManager.OnRenameListener() {
                            @Override
                            public void onSuccess(String newName, String newPath) {
                                updateSelectMode(false);
                                onSelectModelChangeListener.onChange(false);
                                //更新数据
                                //getData();
                                renameFile.setFileName(newName);
                                renameFile.setFilePath(newPath);
                                docsRVAdapter.notifyDataSetChanged();
                                //showToast("rename success");
                            }

                            @Override
                            public void onFailed() {
                                showToast("Rename failure");
                            }
                        });
                break;
            case R.id.delete_tv:
                DialogManager.deleteFileDialog(getActivity(), new DialogManager.OnDialogClickListener() {
                    @Override
                    public void onOKClick(Object data) {
                        //即将删除的文件路径
                        List<String> deleteFilePaths = new ArrayList<>();
                        //需要adapter更新的item位置
                        final Set<Integer> positions = new HashSet<>();

                        //遍历选中的数据
                        for (FileBean fileBean : docsRVAdapter.getSelectDocs()) {
                            //拿到当前数据的路径
                            final String beanPath = fileBean.getFilePath();
                            //删除此文件
                            if(com.wptk.filemanager.utils.FileUtils.deleteFile(beanPath)){
                                deleteFilePaths.add(beanPath);
                            }
                        }
                        //showToast("delete success for "+deleteFilePaths.size()+" file");
                        //通知数据库更新已经删除的路径文件
                        ((BaseActivity)getActivity()).notifyFileIsDeleted(deleteFilePaths);

                        updateSelectMode(false);
                        onSelectModelChangeListener.onChange(false);
                        getData();
                    }
                });
                break;
        }
    }

    @Override
    public void onLongClick(FileBean fileBean) {
        updateSelectMode(true);
        onSelectModelChangeListener.onChange(true);
        checkState();
    }


    public void notifyCheckAll(boolean isCheck){
        docsRVAdapter.checkAllOf(isCheck);
        checkState();
    }


    public void updateSelectMode(boolean isSelect) {
        if(isSelect){
            modifyLl.setVisibility(View.VISIBLE);
        }else{
            modifyLl.setVisibility(View.GONE);
        }
        docsRVAdapter.setSelectModel(isSelect);
        docsRVAdapter.getSelectDocs().clear();
        docsRVAdapter.notifyDataSetChanged();
    }

    private void checkState() {

        if (docsRVAdapter.getSelectDocs().size() == 1) {
            renameTv.setEnabled(true);
        } else {
            renameTv.setEnabled(false);
        }
        if (docsRVAdapter.getSelectDocs().size() == 0) {
            deleteTv.setEnabled(false);
        } else {
            deleteTv.setEnabled(true);
        }
    }

    @Override
    public void onClick(View view, FileBean fileBean) {
        if(docsRVAdapter.isSelectModel()){
            checkState();
        }else{
            ZFileUtil.openFile(fileBean.getFilePath(), view);
        }
    }
}
